
package com.kugou.game.sdk.protocol;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.kugou.framework.base.AppException;
import com.kugou.framework.base.LogUtil;
import com.kugou.framework.http.KGHttpClient;
import com.kugou.framework.http.ResponsePackage;
import com.kugou.game.sdk.entity.ExchangeRatio;
import com.kugou.game.sdk.entity.RechargeDiscount;
import com.kugou.game.sdk.entity.ResponseMessage;
import com.kugou.game.sdk.utils.ProtocolCmd;

/**
 * 描述:请求游戏兑换比例详情业务类
 * 
 * @author liux
 * @since 2014-8-15 下午03:38:33
 */
public class RequestExchangeInfoTask {

    private ArrayList<String> mCmdList = new ArrayList<String>();

    public ExchangeRatioResponse request(String chargeType) {
        ArrayList<HashMap<String, Object>> requestParams = new ArrayList<HashMap<String, Object>>();
        // 填充参数，key-value。key是接口要求传的变量名称
        HashMap<String, Object> params = new HashMap<String, Object>();

        params.put("cmd", ProtocolCmd.CMD_EXCHANGE);
        params.put("chargetype", chargeType);
        requestParams.add(params);

        HashMap<String, Object> gameExchangeParams = new HashMap<String, Object>();
        gameExchangeParams.put("cmd", ProtocolCmd.CMD_GAME_EXCHANGE);
        requestParams.add(gameExchangeParams);
        mCmdList.add(ProtocolCmd.CMD_EXCHANGE);
        mCmdList.add(ProtocolCmd.CMD_GAME_EXCHANGE);

        // 生成请求包
        HttpBaseRequestPackage requestPackage = new HttpBaseRequestPackage();
        // 生成响应包
        ResponsePackage responsePackage = new HttpResponsePackage();
        // 生成响应类
        ExchangeRatioResponse appsHttpResponse = new ExchangeRatioResponse();

        requestPackage.setRequestParams(requestParams);

        try {
            KGHttpClient.request(requestPackage, responsePackage);
            // 响应类赋值
            responsePackage.getResponseData(appsHttpResponse);
            // 返回响应类
            return appsHttpResponse;
        } catch (AppException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 响应包
    private class HttpResponsePackage extends HttpBaseResponsePackage<ExchangeRatioResponse> {

        @Override
        protected void handleResponse(ExchangeRatioResponse response, String jsonStr) {
            try {
                LogUtil.d("response", "RequestExchangeInfoTask:" + jsonStr);
                JSONArray responseArray = new JSONArray(jsonStr);
                int size = responseArray.length();
                HashMap<String, ArrayList<ExchangeRatio>> ratioMap = new HashMap<String, ArrayList<ExchangeRatio>>();
                for (int i = 0; i < size; i++) {
                    if (i >= mCmdList.size()) {
                        break;
                    }
                    JSONObject jsonResp = responseArray.getJSONObject(i);
                    String cmd = jsonResp.optString("cmd");
                    String code = jsonResp.optString("code");
                    String message = jsonResp.optString("message");
                    String prompt = jsonResp.optString("prompt");
                    response.setCode(code);
                    response.setMessage(message);
                    response.setPrompt(prompt);

                    // 根据cmd解析每个请求
                    if (ProtocolCmd.CMD_EXCHANGE.equalsIgnoreCase(cmd) && response.isUseful()) {
                        JSONObject resultResp = jsonResp.optJSONObject("data");
                        // 手机卡兑换比例
                        JSONArray phoneArray = resultResp.getJSONArray("charge_28");
                        ArrayList<ExchangeRatio> phoneRatio = handleArray(phoneArray);
                        ratioMap.put("charge_28", phoneRatio);
                        // 支付宝兑换比例
                        JSONArray aliArray = resultResp.getJSONArray("charge_29");
                        ArrayList<ExchangeRatio> aliRatio = handleArray(aliArray);
                        ratioMap.put("charge_29", aliRatio);
                        // 银联兑换比例
                        JSONArray bankArray = resultResp.getJSONArray("charge_34");
                        ArrayList<ExchangeRatio> bankRatio = handleArray(bankArray);
                        ratioMap.put("charge_34", bankRatio);

                        JSONArray cardArray = resultResp.getJSONArray("charge_43");
                        ArrayList<ExchangeRatio> cardRatio = handleArray(cardArray);
                        ratioMap.put("charge_43", cardRatio);

                        JSONArray smsArray = resultResp.getJSONArray("charge_44");
                        ArrayList<ExchangeRatio> smsRatio = handleArray(smsArray);
                        ratioMap.put("charge_44", smsRatio);

                        JSONArray yiArray = resultResp.getJSONArray("charge_48");
                        ArrayList<ExchangeRatio> yiRatio = handleArray(yiArray);
                        ratioMap.put("charge_48", yiRatio);

                        // 游币兑换比例
                        JSONArray kubiArray = resultResp.getJSONArray("charge_0");
                        ArrayList<ExchangeRatio> kubiRatio = handleArray(kubiArray);
                        ratioMap.put("charge_0", kubiRatio);

                        // 微信兑换比例
                        JSONArray wechatArray = resultResp.getJSONArray("charge_50");
                        ArrayList<ExchangeRatio> wechatlist = handleArray(wechatArray);
                        ratioMap.put("charge_50", wechatlist);

                        // 游币充值比例
                        JSONArray kubiRechargeArray = resultResp.getJSONArray("charge_999");
                        ArrayList<ExchangeRatio> kubiRechargeRatio = handleArray(kubiRechargeArray);
                        ratioMap.put("charge_999", kubiRechargeRatio);

                        JSONObject discountObject = resultResp.optJSONObject("charge_discount");
                        RechargeDiscount discount = handleDiscount(discountObject);
                        response.setDiscount(discount);

                        // 游币充值优惠描述
                        String preferentialString = resultResp.optString("describe");
                        response.setPreferential(preferentialString);

                        response.setYoubiRatio(resultResp.optInt("coinratio", 100));
                    } else if (ProtocolCmd.CMD_GAME_EXCHANGE.equalsIgnoreCase(cmd)
                            && response.isUseful()) {
                        JSONObject resultResp = jsonResp.optJSONObject("data");

                        // 游戏兑换比例
                        JSONArray gameArray = resultResp.optJSONArray("exchangeratio");
                        ArrayList<ExchangeRatio> gameRatio = handleArray(gameArray);
                        ratioMap.put("game", gameRatio);

                        // 游戏币名称
                        String coinName = resultResp.optString("coinname");
                        response.setCoinName(coinName);
                    }

                    if (i == responseArray.length() - 1) {
                        response.setRatioMap(ratioMap);
                        response.setOk(true);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解析兑换比例的json数组为集合
     * 
     * @param array
     * @return
     */
    private ArrayList<ExchangeRatio> handleArray(JSONArray array) {
        try {
            if (array != null && array.length() > 0) {
                ArrayList<ExchangeRatio> ratios = new ArrayList<ExchangeRatio>();
                int len = array.length();
                for (int i = 0; i < len; i++) {
                    JSONObject ratioObj = array.getJSONObject(i);
                    ExchangeRatio ratio = new ExchangeRatio();
                    ratio.setMin(ratioObj.getInt("min"));
                    // 如果返回的最大值是-1，则赋值为最大整数
                    ratio.setMax(ratioObj.getInt("max") == -1 ? Integer.MAX_VALUE : ratioObj
                            .getInt("max"));
                    ratio.setPercent(ratioObj.getDouble("percent"));
                    ratios.add(ratio);
                }
                return ratios;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public class ExchangeRatioResponse extends ResponseMessage {
        private static final long serialVersionUID = -5905989827340308810L;

        private String coinName = "";

        private HashMap<String, ArrayList<ExchangeRatio>> ratioMap;

        private RechargeDiscount discount;

        private int youbiRatio = 100;

        public int getYoubiRatio() {
            return youbiRatio;
        }

        public void setYoubiRatio(int youbiRatio) {
            this.youbiRatio = youbiRatio;
        }

        public RechargeDiscount getDiscount() {
            return discount;
        }

        public void setDiscount(RechargeDiscount discount) {
            this.discount = discount;
        }

        public String getCoinName() {
            return coinName;
        }

        public void setCoinName(String coinName) {
            this.coinName = coinName;
        }

        private String preferential = "";

        public String getPreferential() {
            return preferential;
        }

        public void setPreferential(String pre) {
            preferential = pre;
        }

        public HashMap<String, ArrayList<ExchangeRatio>> getRatioMap() {
            return ratioMap;
        }

        public void setRatioMap(HashMap<String, ArrayList<ExchangeRatio>> ratioMap) {
            this.ratioMap = ratioMap;
        }
    }

    private RechargeDiscount handleDiscount(JSONObject object) {
        if (object == null)
            return null;
        RechargeDiscount discount = new RechargeDiscount();

        discount.setTitle(object.optString("discount_title"));
        discount.setSubTitle(object.optString("discount_sub_title"));
        discount.setDetail(object.optString("discount_detail"));
        discount.setNextRequestLeftTime(object.optInt("lefttime"));

        JSONObject discountRule = object.optJSONObject("discount_rule");
        discount.setDiscountType(discountRule.optInt("type"));
        JSONArray rule = discountRule.optJSONArray("arraylist");
        discount.setmRatio(handleArray(rule));

        return discount;
    }
}
